#include <stdio.h>
#include <string.h>

#include "esp_log.h"
#include "esp_system.h"

#include "wifi_softap.h"
#include "web_server.h"
#include "dns_server.h"
#include "wifi_station.h"
#include "wifi_nvs.h"
#include "esp_wifi_scan.h"

#include "wifi_server.h"

#define TAG "wifi server"

static uint8_t wifi_state = 0;

void wifi_server_task(void)
{
    while (1)
    {
        switch (wifi_state)
        {
        case 0:
            ESP_LOGI(TAG, "wifi scan....");
            wifi_scan();
            wifi_state = 1;
            break;
        case 1:
            ESP_LOGI(TAG, "wifi check nvs....");
            if (Get_nvs_wifi(wifi_name, wifi_password) == 1) // 判断是否有连接标志
            {
                uint8_t flag = 0;
                for (int i = 0; i < SCAN_LIST_SIZE; i++)
                {
                    if (strcmp(wifi_name, scan_ssid[i]) == 0)
                    {
                        flag = 1;
                        break;
                    }
                }

                // 出现相同的
                if (flag)
                {
                    wifi_state = 2;
                }
                else
                {
                    // 清除nvs标记
                    Clear_nvs_wifi_flag();
                    wifi_state = 3;
                }
            }
            else
            {
                wifi_state = 3;
            }
            break;

        case 2:
            ESP_LOGI(TAG, "wifi connect....");
            wifi_normal_connect();
            wifi_state = 4;
            break;

        case 3:
            ESP_LOGI(TAG, "wifi captive portal....");
            captive_portal_init(); // 强制门户认证初始化
            wifi_captive_portal_connect();
            wifi_state = 4;
            break;

        case 4:
            vTaskDelay(1000 / portTICK_PERIOD_MS);
            break;
        }
    }
}
